using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GenerativeAgents.Core;
using GenerativeAgents.Unity;

namespace GenerativeAgents.Unity
{
    /// <summary>
    /// 场景设置器
    /// 负责初始化和配置整个生成式智能体系统
    /// </summary>
    public class SceneSetup : MonoBehaviour
    {
        [Header("场景配置")]
        [SerializeField] private bool autoInitialize = true;
        [SerializeField] private bool createDefaultAgents = true;
        [SerializeField] private int defaultAgentCount = 3;
        [SerializeField] private bool createDefaultEnvironment = true;
        
        [Header("智能体预制件")]
        [SerializeField] private GameObject agentPrefab;
        [SerializeField] private List<AgentConfig> agentConfigs;
        
        [Header("环境预制件")]
        [SerializeField] private GameObject environmentManagerPrefab;
        [SerializeField] private GameObject tilePrefab;
        [SerializeField] private List<GameObject> environmentObjectPrefabs;
        
        [Header("UI预制件")]
        [SerializeField] private GameObject uiCanvasPrefab;
        [SerializeField] private GameObject agentMonitorUIPrefab;
        
        // 系统组件
        private EnvironmentManager environmentManager;
        private List<AgentController> createdAgents;
        private Canvas uiCanvas;
        
        private void Awake()
        {
            if (autoInitialize)
            {
                StartCoroutine(InitializeScene());
            }
        }
        
        /// <summary>
        /// 初始化场景
        /// </summary>
        private IEnumerator InitializeScene()
        {
            Debug.Log("[SceneSetup] Starting scene initialization...");
            
            try
            {
                // 1. 初始化环境系统
                yield return StartCoroutine(SetupEnvironment());
                
                // 2. 创建智能体
                yield return StartCoroutine(CreateAgents());
                
                // 3. 设置UI系统
                yield return StartCoroutine(SetupUI());
                
                // 4. 创建环境对象
                yield return StartCoroutine(CreateEnvironmentObjects());
                
                // 5. 最终配置
                yield return StartCoroutine(FinalizeSetup());
                
                Debug.Log("[SceneSetup] Scene initialization completed successfully!");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[SceneSetup] Error during scene initialization: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 设置环境
        /// </summary>
        private IEnumerator SetupEnvironment()
        {
            Debug.Log("[SceneSetup] Setting up environment...");
            
            // 创建环境管理器
            if (environmentManager == null)
            {
                if (environmentManagerPrefab != null)
                {
                    var envObject = Instantiate(environmentManagerPrefab);
                    environmentManager = envObject.GetComponent<EnvironmentManager>();
                }
                else
                {
                    var envObject = new GameObject("EnvironmentManager");
                    environmentManager = envObject.AddComponent<EnvironmentManager>();
                }
            }
            
            yield return new WaitForSeconds(0.1f);
            
            // 等待环境管理器初始化完成
            while (environmentManager == null)
            {
                yield return null;
            }
            
            Debug.Log("[SceneSetup] Environment setup completed");
        }
        
        /// <summary>
        /// 创建智能体
        /// </summary>
        private IEnumerator CreateAgents()
        {
            Debug.Log("[SceneSetup] Creating agents...");
            
            createdAgents = new List<AgentController>();
            
            if (createDefaultAgents)
            {
                for (int i = 0; i < defaultAgentCount; i++)
                {
                    var agent = CreateSingleAgent(i);
                    if (agent != null)
                    {
                        createdAgents.Add(agent);
                        
                        // 注册到环境管理器
                        if (environmentManager != null)
                        {
                            environmentManager.RegisterAgent(agent);
                        }
                        
                        yield return new WaitForSeconds(0.1f); // 避免同时初始化太多智能体
                    }
                }
            }
            
            Debug.Log($"[SceneSetup] Created {createdAgents.Count} agents");
        }
        
        /// <summary>
        /// 创建单个智能体
        /// </summary>
        private AgentController CreateSingleAgent(int index)
        {
            try
            {
                GameObject agentObject;
                
                if (agentPrefab != null)
                {
                    agentObject = Instantiate(agentPrefab);
                }
                else
                {
                    agentObject = new GameObject($"Agent_{index}");
                    agentObject.AddComponent<AgentController>();
                }
                
                var agentController = agentObject.GetComponent<AgentController>();
                if (agentController == null)
                {
                    agentController = agentObject.AddComponent<AgentController>();
                }
                
                // 配置智能体
                ConfigureAgent(agentController, index);
                
                // 设置位置
                var spawnPosition = GetSpawnPosition(index);
                agentObject.transform.position = spawnPosition;
                
                return agentController;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[SceneSetup] Error creating agent {index}: {ex.Message}");
                return null;
            }
        }
        
        /// <summary>
        /// 配置智能体
        /// </summary>
        private void ConfigureAgent(AgentController agent, int index)
        {
            string agentName;
            string personality;
            Vector3 spawnPos = GetSpawnPosition(index);
            
            // 使用预定义配置或生成默认配置
            if (agentConfigs != null && index < agentConfigs.Count)
            {
                var config = agentConfigs[index];
                agentName = config.agentName;
                personality = config.personality;
                if (config.spawnPosition != Vector3.zero)
                {
                    spawnPos = config.spawnPosition;
                }
            }
            else
            {
                agentName = GenerateAgentName(index);
                personality = GenerateAgentPersonality(index);
            }
            
            agent.SetAgentConfiguration(agentName, personality, spawnPos);
            
            Debug.Log($"[SceneSetup] Configured agent: {agentName} with personality: {personality}");
        }
        
        /// <summary>
        /// 生成智能体名称
        /// </summary>
        private string GenerateAgentName(int index)
        {
            var names = new[] { "Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Grace", "Henry" };
            return index < names.Length ? names[index] : $"Agent_{index}";
        }
        
        /// <summary>
        /// 生成智能体个性
        /// </summary>
        private string GenerateAgentPersonality(int index)
        {
            var personalities = new[]
            {
                "Friendly and outgoing, loves meeting new people",
                "Quiet and thoughtful, prefers reading and learning",
                "Energetic and curious, always exploring new places",
                "Calm and helpful, enjoys helping others",
                "Creative and artistic, likes to appreciate beauty",
                "Analytical and logical, enjoys solving problems"
            };
            
            return index < personalities.Length ? personalities[index] : "Balanced and adaptable individual";
        }
        
        /// <summary>
        /// 获取生成位置
        /// </summary>
        private Vector3 GetSpawnPosition(int index)
        {
            // 围成圆形分布
            float angle = (index * 360f / defaultAgentCount) * Mathf.Deg2Rad;
            float radius = 15f;
            
            var x = Mathf.Cos(angle) * radius;
            var z = Mathf.Sin(angle) * radius;
            
            return new Vector3(x, 0, z);
        }
        
        /// <summary>
        /// 设置UI
        /// </summary>
        private IEnumerator SetupUI()
        {
            Debug.Log("[SceneSetup] Setting up UI...");
            
            // 创建UI Canvas
            if (uiCanvasPrefab != null)
            {
                var canvasObject = Instantiate(uiCanvasPrefab);
                uiCanvas = canvasObject.GetComponent<Canvas>();
            }
            else
            {
                var canvasObject = new GameObject("UI Canvas");
                uiCanvas = canvasObject.AddComponent<Canvas>();
                uiCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
                canvasObject.AddComponent<UnityEngine.UI.CanvasScaler>();
                canvasObject.AddComponent<UnityEngine.UI.GraphicRaycaster>();
            }
            
            // 创建智能体监控UI
            if (agentMonitorUIPrefab != null && uiCanvas != null)
            {
                var monitorUIObject = Instantiate(agentMonitorUIPrefab, uiCanvas.transform);
                var monitorUI = monitorUIObject.GetComponent<AgentMonitorUI>();
                
                if (monitorUI != null)
                {
                    Debug.Log("[SceneSetup] Agent monitor UI created");
                }
            }
            
            yield return new WaitForSeconds(0.1f);
            
            Debug.Log("[SceneSetup] UI setup completed");
        }
        
        /// <summary>
        /// 创建环境对象
        /// </summary>
        private IEnumerator CreateEnvironmentObjects()
        {
            Debug.Log("[SceneSetup] Creating environment objects...");
            
            if (createDefaultEnvironment && environmentObjectPrefabs != null)
            {
                foreach (var prefab in environmentObjectPrefabs)
                {
                    if (prefab != null)
                    {
                        var position = GetRandomEnvironmentPosition();
                        var envObject = Instantiate(prefab, position, Quaternion.identity);
                        
                        // 确保有EnvironmentObject组件
                        var envObjectComponent = envObject.GetComponent<EnvironmentObject>();
                        if (envObjectComponent == null)
                        {
                            envObjectComponent = envObject.AddComponent<EnvironmentObject>();
                        }
                        
                        yield return new WaitForSeconds(0.05f);
                    }
                }
            }
            
            // 创建一些默认环境对象
            CreateDefaultEnvironmentObjects();
            
            Debug.Log("[SceneSetup] Environment objects created");
        }
        
        /// <summary>
        /// 创建默认环境对象
        /// </summary>
        private void CreateDefaultEnvironmentObjects()
        {
            // 咖啡厅桌子
            CreateEnvironmentObject("Cafe Table", ObjectType.Furniture, new Vector3(-20, 0, 0));
            
            // 公园长椅
            CreateEnvironmentObject("Park Bench", ObjectType.Furniture, new Vector3(20, 0, 0));
            
            // 装饰花坛
            CreateEnvironmentObject("Flower Bed", ObjectType.Decoration, new Vector3(25, 0, 5));
            
            // 信息亭
            CreateEnvironmentObject("Info Kiosk", ObjectType.Interactive, new Vector3(0, 0, 0));
        }
        
        /// <summary>
        /// 创建环境对象
        /// </summary>
        private void CreateEnvironmentObject(string name, ObjectType type, Vector3 position)
        {
            var obj = new GameObject(name);
            obj.transform.position = position;
            
            // 添加基础组件
            obj.AddComponent<BoxCollider>();
            var renderer = obj.AddComponent<MeshRenderer>();
            var meshFilter = obj.AddComponent<MeshFilter>();
            
            // 创建简单的立方体网格
            meshFilter.mesh = CreateSimpleCubeMesh();
            
            // 设置材质颜色
            var material = new Material(Shader.Find("Standard"));
            material.color = GetObjectTypeColor(type);
            renderer.material = material;
            
            // 添加环境对象组件
            var envObject = obj.AddComponent<EnvironmentObject>();
            
            Debug.Log($"[SceneSetup] Created environment object: {name}");
        }
        
        /// <summary>
        /// 创建简单立方体网格
        /// </summary>
        private Mesh CreateSimpleCubeMesh()
        {
            var mesh = new Mesh();
            
            // 简化的立方体顶点
            Vector3[] vertices = {
                new Vector3(-0.5f, -0.5f, -0.5f),
                new Vector3(0.5f, -0.5f, -0.5f),
                new Vector3(0.5f, 0.5f, -0.5f),
                new Vector3(-0.5f, 0.5f, -0.5f),
                new Vector3(-0.5f, -0.5f, 0.5f),
                new Vector3(0.5f, -0.5f, 0.5f),
                new Vector3(0.5f, 0.5f, 0.5f),
                new Vector3(-0.5f, 0.5f, 0.5f)
            };
            
            int[] triangles = {
                0, 2, 1, 0, 3, 2,
                2, 3, 4, 2, 4, 5,
                1, 2, 5, 5, 2, 6,
                0, 7, 4, 0, 4, 3,
                5, 4, 7, 5, 7, 6,
                0, 6, 7, 0, 1, 6
            };
            
            mesh.vertices = vertices;
            mesh.triangles = triangles;
            mesh.RecalculateNormals();
            
            return mesh;
        }
        
        /// <summary>
        /// 获取对象类型颜色
        /// </summary>
        private Color GetObjectTypeColor(ObjectType type)
        {
            switch (type)
            {
                case ObjectType.Furniture: return Color.brown;
                case ObjectType.Decoration: return Color.green;
                case ObjectType.Interactive: return Color.blue;
                case ObjectType.Tool: return Color.yellow;
                case ObjectType.Container: return Color.gray;
                default: return Color.white;
            }
        }
        
        /// <summary>
        /// 获取随机环境位置
        /// </summary>
        private Vector3 GetRandomEnvironmentPosition()
        {
            var x = UnityEngine.Random.Range(-30f, 30f);
            var z = UnityEngine.Random.Range(-30f, 30f);
            return new Vector3(x, 0, z);
        }
        
        /// <summary>
        /// 最终配置
        /// </summary>
        private IEnumerator FinalizeSetup()
        {
            Debug.Log("[SceneSetup] Finalizing setup...");
            
            // 确保所有智能体都已注册
            foreach (var agent in createdAgents)
            {
                if (agent != null && environmentManager != null)
                {
                    environmentManager.RegisterAgent(agent);
                }
            }
            
            // 设置相机位置（如果存在）
            var mainCamera = Camera.main;
            if (mainCamera != null)
            {
                mainCamera.transform.position = new Vector3(0, 20, -10);
                mainCamera.transform.LookAt(Vector3.zero);
            }
            
            yield return new WaitForSeconds(0.1f);
            
            Debug.Log("[SceneSetup] Setup finalization completed");
        }
        
        /// <summary>
        /// 手动初始化场景
        /// </summary>
        [ContextMenu("Initialize Scene")]
        public void ManualInitialize()
        {
            StartCoroutine(InitializeScene());
        }
        
        /// <summary>
        /// 清理场景
        /// </summary>
        [ContextMenu("Cleanup Scene")]
        public void CleanupScene()
        {
            // 清理创建的智能体
            if (createdAgents != null)
            {
                foreach (var agent in createdAgents)
                {
                    if (agent != null)
                    {
                        DestroyImmediate(agent.gameObject);
                    }
                }
                createdAgents.Clear();
            }
            
            // 清理环境管理器
            if (environmentManager != null)
            {
                DestroyImmediate(environmentManager.gameObject);
                environmentManager = null;
            }
            
            // 清理UI
            if (uiCanvas != null)
            {
                DestroyImmediate(uiCanvas.gameObject);
                uiCanvas = null;
            }
            
            // 清理环境对象
            var envObjects = FindObjectsOfType<EnvironmentObject>();
            foreach (var obj in envObjects)
            {
                DestroyImmediate(obj.gameObject);
            }
            
            Debug.Log("[SceneSetup] Scene cleanup completed");
        }
        
        /// <summary>
        /// 获取创建的智能体列表
        /// </summary>
        public List<AgentController> GetCreatedAgents()
        {
            return new List<AgentController>(createdAgents ?? new List<AgentController>());
        }
        
        /// <summary>
        /// 获取环境管理器
        /// </summary>
        public EnvironmentManager GetEnvironmentManager()
        {
            return environmentManager;
        }
    }
    
    /// <summary>
    /// 智能体配置
    /// </summary>
    [System.Serializable]
    public class AgentConfig
    {
        public string agentName;
        public string personality;
        public Vector3 spawnPosition;
        public List<string> initialGoals;
        public List<string> initialHabits;
        
        public AgentConfig()
        {
            initialGoals = new List<string>();
            initialHabits = new List<string>();
        }
    }
}